// 管理用户相关信息的 store
import {defineStore} from 'pinia'
import {loginAPI, getInfo, logout} from '@/api/login'
import {ElMessage} from "element-plus";
import {getToken, setToken, removeToken} from '@/utils/auth'
import router from "@/router/index.js";

export const useUserStore = defineStore('user', {
    state: () => {
        return {
            token: getToken(),
            avatar: '',
            name: '',
            roles: [],
        }
    },
    actions: {
        async gotoLogin(username, password) {
            const res = await loginAPI(username, password);
            if (res.status === 200) {
                const tokenStr = res.data.data.tokenHead + res.data.data.token;
                setToken(tokenStr);
                localStorage.setItem('MAC-USERINFO', tokenStr);
                ElMessage.success("登录成功！！！");
            } else {
                ElMessage.error("登录失败xctvybunimo,l！！！");
            }
        },
        async getInfo() {
            const userToken = localStorage.getItem('MAC-USERINFO');
            if (userToken) {
                const res = await getInfo();
                this.name = res.data.data.username;
                this.avatar = res.data.data.icon;
                this.roles = res.data.data.roles;
            } else {
                ElMessage.error("用户信息获取失败！");
            }
        },
        async logout() {
            removeToken()
            await router.push('/login')
            localStorage.removeItem('MAC-USERINFO')
        }
    },
})
